package com.sxm.yiwei.activitis;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.view.ContextThemeWrapper;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.BaseIntents;
import com.sxm.yiwei.tools.CircleTransform;
import com.sxm.yiwei.tools.CropPictures;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MineMsgHead extends BaseActivity implements View.OnClickListener{

    private String TAG = "tou";
    private Button msgmsgphoto;
    private ImageView msgheadimg,headback;
    /*用来标识请求照相功能的activity*/
    private static final int CAMERA_WITH_DATA = 3023;
    /*用来标识请求gallery的activity*/
    private static final int PHOTO_PICKED_WITH_DATA = 3021;
    private static final int PHOTO_TEXT = 3022;
    private static  int index = 0;
    private ArrayList<String> mList = new ArrayList<String>();
    private List<Object> imgId = new ArrayList<>();
    /*拍照的照片存储位置*/
    private static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory()+ "/DCIM/Camera");
    private File mCurrentPhotoFile;

    // 按钮标志
    private int currentIndex;
    private Button upimgbt;
    private Button upimg;
    private String appId;
    private String userId;
    private String token;
    private String path;

    private String s1;


    private Bitmap photo;
    private Bitmap bitmap;
    private String path1;

    private String avatar;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    Picasso.with(MineMsgHead.this).load(InternetAddressUtis.IMG_URL+ avatar).transform(new CircleTransform()).into(msgheadimg);

                    break;
            }
        }
    };
    private AlertDialog dialog;
    private String imgpath = null;
    private BaseIntents baseIntents;
    private ImageView backmain;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_msg_head);

        initview();

        SharedPreferences sharedPreferences = getSharedPreferences("userlogin",Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid","1");
        userId = sharedPreferences.getString("userId", "0");
        token = sharedPreferences.getString("token", "2");
        avatar = MainActivity.a;
        baseIntents = new BaseIntents();
        Log.d(TAG, "onCreate: 头像--"+avatar);
       Picasso.with(this).load(InternetAddressUtis.IMG_URL+ avatar).transform(new CircleTransform()).into(msgheadimg);

    }
    private void initview() {
        backmain = (ImageView) findViewById(R.id.minemsghead_backmain);
        upimg = (Button) findViewById(R.id.msgmsg_upimgbt);
        msgmsgphoto = (Button) findViewById(R.id.msgmsg_photo);
        msgheadimg = (ImageView) findViewById(R.id.msg_headimg);
        headback = (ImageView) findViewById(R.id.msg_head_back);
        // 设置点击事件
         headback.setOnClickListener(this);
        upimg.setOnClickListener(this);
        msgmsgphoto.setOnClickListener(this);
        upimg.setOnClickListener(this);
        backmain.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.msg_head_back:
                finish();
                break;
            case R.id.msg_headimg:
                break;
            case R.id.msgmsg_photo:
                doPickPhotoAction();

                break;
            case R.id.msgmsg_upimgbt:
                // 开启子线程上传头像
                if (imgpath==null){
                    Toast.makeText(this, "请选择图片", Toast.LENGTH_SHORT).show();
                }else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MineMsgHead.this,R.style.NoBackGroundDialog);
                    View view = LayoutInflater.from(this).inflate(R.layout.progress_dialog, null);
                    builder.setView(view);
                    dialog = builder.create();
                    dialog.show();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            upImg();

                        }
                    }).start();
                }
                break;
        }
    }
        // 上传照片
    private void upImg() {

        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/user/uploadAvatar");

        File file = new File(imgpath);
        params.addHeader("Content-Type","multipart/form-data");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        params.addHeader("imgType", "1");
        params.setMultipart(true);
        params.addBodyParameter("avatar",file);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                //handler.sendEmptyMessage(1);
                Toast.makeText(MineMsgHead.this, "头像设置成功", Toast.LENGTH_SHORT).show();

            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {



            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                dialog.dismiss();
            }
        });
    }
    // 弹窗 提示选择获取方式
    private void doPickPhotoAction() {
        final Context context = this;
        AlertDialog.Builder b1 = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.picture_dialog, null);
        b1.setView(view);

        TextView camere = (TextView) view.findViewById(R.id.picdia_camere);
        TextView pic = (TextView) view.findViewById(R.id.picdia_pic);
        TextView cancel1 = (TextView) view.findViewById(R.id.picdia_cancel);

        final AlertDialog dialog1 = b1.create();
        Window window = dialog1.getWindow();
        camere.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String status= Environment.getExternalStorageState();
                if(status.equals(Environment.MEDIA_MOUNTED)){//判断是否有SD卡
                    // index=0;
                    baseIntents.doTakePhoto();// 用户点击了从照相机获取
                    dialog1.dismiss();
                }
                else{
                    Toast.makeText(context, "没有SD卡", Toast.LENGTH_SHORT).show();
                }
            }
        });
        pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baseIntents.doPickPhotoFromGallery();// 从相册中去获取
                dialog1.dismiss();
            }
        });
        cancel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
            }
        });
        dialog1.show();
        window.setGravity(Gravity.BOTTOM);
    }

    // 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
                photo = data.getParcelableExtra("data");
                imgpath = CropPictures.saveBitmapFile(photo, baseIntents.getPhotoFileName());
                Picasso.with(MineMsgHead.this).load(new File(imgpath)).transform(new CircleTransform()).into(msgheadimg);
                break;
            }
            case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
                baseIntents.doCropPhoto(baseIntents.mCurrentPhotoFile);
                break;
        }
            case PHOTO_TEXT:
                Uri data1 = data.getData();
                if (!TextUtils.isEmpty(data1.getAuthority())){
                    ContentResolver resolver = getContentResolver();
                    try {
                        photo = MediaStore.Images.Media.getBitmap(resolver, data1);
                        String[] proj = {MediaStore.Images.Media.DATA};
                        Cursor cursor = managedQuery(data1, proj, null, null, null);
                        if (cursor==null){
                            Toast.makeText(this, "没有找到图片", Toast.LENGTH_SHORT).show();
                        }else {
                            cursor.moveToFirst();
                            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            //图片路径
                            path1 = cursor.getString(column_index);

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    path1 = data1.getPath();
                }
                File file = new File(path1);
                baseIntents.doCropPhoto(file);
                break;
        }
    }

}
